import React from 'react'
import { Navigate, useLocation } from 'react-router-dom'

interface AuthGuardProps {
  children: React.ReactNode
}

// 模拟的身份验证状态检查
const useAuth = () => {
  // 这里可以集成实际的认证逻辑
  // 目前简单检查 localStorage 中是否有 token
  const [isAuthenticated, setIsAuthenticated] = React.useState<boolean | null>(null)

  React.useEffect(() => {
    // 模拟异步检查认证状态
    const checkAuth = () => {
      const token = localStorage.getItem('token')
      setIsAuthenticated(!!token)
    }
    
    checkAuth()
  }, [])

  return { isAuthenticated, setIsAuthenticated }
}

// 需要认证的路由守卫
export const AuthGuard: React.FC<AuthGuardProps> = ({ children }) => {
  const { isAuthenticated } = useAuth()
  const location = useLocation()

  // 如果还在检查认证状态，显示加载状态
  if (isAuthenticated === null) {
    return (
      <div className="flex items-center justify-center h-screen">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
      </div>
    )
  }

  // 如果未认证，重定向到登录页
  if (!isAuthenticated) {
    return <Navigate to="/login" state={{ from: location }} replace />
  }

  return <>{children}</>
}

// 登录页面守卫（已登录用户访问登录页时重定向）
export const LoginGuard: React.FC<AuthGuardProps> = ({ children }) => {
  const { isAuthenticated } = useAuth()
  const location = useLocation()

  // 如果还在检查认证状态，显示加载状态
  if (isAuthenticated === null) {
    return (
      <div className="flex items-center justify-center h-screen">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
      </div>
    )
  }

  // 如果已认证，重定向到 from 参数指定的页面或首页
  if (isAuthenticated) {
    const from = (location.state as any)?.from?.pathname || '/home'
    return <Navigate to={from} replace />
  }

  return <>{children}</>
}

// 认证工具函数
export const authUtils = {
  // 登录
  login: (token: string) => {
    localStorage.setItem('token', token)
  },
  
  // 登出
  logout: () => {
    localStorage.removeItem('token')
  },
  
  // 检查是否已登录
  isLoggedIn: () => {
    return !!localStorage.getItem('token')
  }
}